<?php
require_once ("./lib/yop/YopClient3.php");
require_once ("./lib/yop/Util/YopSignUtils.php");

require_once ("Utils.php");

class YopOrder {
    public function __construct() {
        
    }
    
    private function getString($response) {
        $str = "";
        foreach ($response as $key => $value) {
            $str .= $key . "=" . $value . "&";
        }
        $getSign = substr($str, 0, strlen($str) - 1);
        return $getSign;
    }
 
    private function getUrl($response,$private_key) {
        $content = $this->getString($response);
        $sign = YopSignUtils::signRsa($content,$private_key);
        $url = $content."&sign=".$sign;
        return $url;
    }
     
    public function reqYopData($postData) {
        $data = $postData['source'];
        
        $goodsParamExtArr = array( // 商品信息
            "goodsName" => $data['pay_productname'],
            "goodsDesc" => $data['pay_productdesc']
        );
        $payAmount = sprintf("%.2f", $data['pay_amount'] / 100); // 订单金额
        $goodsParamExtJson = json_encode($goodsParamExtArr, 320);
        $request = new YopRequest("OPR:" . $postData['parent_merchant_id'], $postData['private_key'], "https://open.yeepay.com/yop-center", $postData['public_key']);
        $request->addParam("parentMerchantNo", $postData['group_merchant_id']);
        $request->addParam("merchantNo",       $postData['parent_merchant_id']);
        $request->addParam("orderId",          $data['mchnt_orderid']);   // 商户订单号
        $request->addParam("orderAmount",      $payAmount); // 订单金额
        $request->addParam("timeoutExpress",   $data['timeout_express']); // 订单有效期
        $request->addParam("requestDate",      $data['request_date']);    // 请求时间
        $request->addParam("redirectUrl",      $data['pay_redirecturl']); // 支付成功页面回调地址
        $request->addParam("notifyUrl",        $postData['callbackurl']); // 异步通知，支付成功服务器回调
        $request->addParam("goodsParamExt",    $goodsParamExtJson);  // 商品信息，由商品名称与商品描述拼装而成的JSON
        $request->addParam("paymentParamExt",  null); // 支付扩展参数
        $request->addParam("industryParamExt", null); // 行业扩展参数                              
        $request->addParam("memo",             null); // 自定义对账备注
        $request->addParam("riskParamExt",     null); // 风控信息
        $request->addParam("csUrl",            null); // 清算成功回调地址
        // 资金处理类型，DELAY_SETTLE("延迟结算")，REAL_TIME("实时订单")，REAL_TIME_DIVIDE（“实时分账”），REAL_TIME_SPLIT_ACCOUNT_IN( "实时拆分入账");
        $request->addParam("fundProcessType",  'REAL_TIME');
        $request->addParam("divideDetail",     null);// 分账明细
        $request->addParam("divideNotifyUrl",  null); // 分账回调地址
        $response = YopClient3::post("/rest/v1.0/sys/trade/order", $request);
        $resData = Utils::objectToArray($response);
        if($resData['result'] == NULL) {
            $resultArr = array(
                "code"    => false,
                "msg"     => $resData['error'],
            );
            return json_encode($resultArr, 320);
        } else { // 检验签名等 
            return $this->verifySign($postData, $data, $response, $resData);
        }
    }
    
    /*
     * 检验签名等 
     */
    private function verifySign($postData, $data, $response, $resData) {
        if($response->validSign == 1) { // 平台内部签名验证成功
            // 取得返回结果
            if($resData['result']['code'] == 'OPR00000') { // 下单成功
                // 获取支付地址
                $url = $this->packageUrl($postData, $data, $resData['result']);  
                $resultArr = array(
                    "code"    => true,
                    "msg"     => '平台内部签名验证成功',
                    "url"     => $url,
                    "source"  => $resData['result']
                );
            } else {
                $resultArr = array(
                    "code"    => false,
                    "msg"     => '下单失败',
                );
            }
        } else {
            $resultArr = array(
                "code"    => false,
                "msg"     => '平台内部签名验证失败',
            );
        }
        return json_encode($resultArr, 320);
    }
    
    /*
     * 组装支付地址
     */
    private function packageUrl($postData, $data, $resData) {
        $token = $resData['token'];
        $cashter = array(
            "merchantNo"    => $postData['parent_merchant_id'],
            "token"         => $token,
            "timestamp"     => $data['timestamp'],
            "directPayType" => $data['pay_tradetype'],
            "cardType"      => null, // 限制交易的卡类型
            "userNo"        => $data['user_id'],
            "userType"      => $data['user_type'],
            "ext"           => null, // 扩展字段
        ); 
        $getUrl = $this->getUrl($cashter, $postData['private_key']);   
        $newUrl = str_replace("&timestamp", "&amp;timestamp", $getUrl);
        $url = "https://cash.yeepay.com/cashier/std?" . $newUrl;
        return $url;
    }
    
}
